<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  VideoPlay,
  Search,
  Plus,
  Edit,
  Delete,
  Picture,
  Upload,
  Document
} from '@element-plus/icons-vue'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const videos = ref<any[]>([])
const channels = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const search = ref('')

// 对话框状态
const showUploadDialog = ref(false)
const uploading = ref(false)

// 上传表单数据
const uploadForm = ref({
  title: '',
  description: '',
  channelId: ''
})

// 文件相关
const videoFileList = ref<any[]>([])
const coverFileList = ref<any[]>([])
const videoInput = ref<HTMLInputElement | null>(null)
const coverInput = ref<HTMLInputElement | null>(null)

// API基础URL
const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

// 计算属性
const hasVideos = computed(() => videos.value.length > 0)
const isSearching = computed(() => search.value.trim().length > 0)
const canUpload = computed(() => {
  return uploadForm.value.title.trim() &&
         uploadForm.value.channelId &&
         videoFileList.value.length > 0
})

// 获取비디오 목록
const fetchVideos = async () => {
  loading.value = true
  try {
    const params: any = {
      page: currentPage.value,
      limit: pageSize.value
    }
    if (search.value.trim()) {
      params.search = search.value.trim()
    }

    const response = await request.get('/api/admin/videos', { params })
    videos.value = response.data.videos || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('비디오 목록 가져오기 실패:', error)
    ElMessage.error('비디오 목록을 가져오는데 실패했습니다')
  } finally {
    loading.value = false
  }
}

// 获取채널列表
const fetchChannels = async () => {
  try {
    const response = await request.get('/api/admin/channels', { params: { limit: 200 } })
    channels.value = response.data.channels || []
  } catch (error) {
    console.error('채널 목록 가져오기 실패:', error)
    ElMessage.error('채널 목록을 가져오는데 실패했습니다')
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchVideos()
}

// 清空搜索
const clearSearch = () => {
  search.value = ''
  currentPage.value = 1
  fetchVideos()
}

// 打开上传对话框
const openUpload = () => {
  uploadForm.value = {
    title: '',
    description: '',
    channelId: ''
  }
  videoFileList.value = []
  coverFileList.value = []
  showUploadDialog.value = true
}

// 选择비디오文件
const selectVideo = () => {
  videoInput.value?.click()
}

// 选择커버文件
const selectCover = () => {
  coverInput.value?.click()
}

// 处理비디오文件选择
const handleVideoSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('video/')) {
    ElMessage.error('비디오 파일을 선택해주세요')
    return
  }

  // 检查文件大小 (2GB)
  if (file.size > 2 * 1024 * 1024 * 1024) {
    ElMessage.error('비디오 파일은 2GB를 초과할 수 없습니다')
    return
  }

  videoFileList.value = [{ name: file.name, raw: file }]
}

// 处理커버文件选择
const handleCoverSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('이미지 파일을 선택해주세요')
    return
  }

  // 检查文件大小 (10MB)
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('이미지 파일은 10MB를 초과할 수 없습니다')
    return
  }

  coverFileList.value = [{ name: file.name, raw: file }]
}

// 上传비디오
const uploadVideo = async () => {
  if (!canUpload.value) {
    ElMessage.error('제목, 채널, 비디오 파일을 모두 입력해주세요')
    return
  }

  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('title', uploadForm.value.title)
    formData.append('description', uploadForm.value.description)
    formData.append('channelId', uploadForm.value.channelId)
    formData.append('video', videoFileList.value[0].raw)

    if (coverFileList.value.length > 0) {
      formData.append('cover', coverFileList.value[0].raw)
    }

    await request.post('/api/admin/videos/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    ElMessage.success('비디오 업로드 성공')
    showUploadDialog.value = false
    fetchVideos()
  } catch (error) {
    console.error('비디오 업로드 실패:', error)
    ElMessage.error('비디오 업로드 실패')
  } finally {
    uploading.value = false
  }
}

// 删除비디오
const deleteVideo = async (video: any) => {
  try {
    await ElMessageBox.confirm(
      '이 비디오를 삭제하시겠습니까?',
      '삭제 확인',
      {
        confirmButtonText: '삭제',
        cancelButtonText: '취소',
        type: 'warning'
      }
    )

    video.deleting = true
    await request.delete(`/api/admin/videos/${video.id}`)
    ElMessage.success('비디오 삭제 성공')
    fetchVideos()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('비디오 삭제 실패:', error)
      ElMessage.error('비디오 삭제 실패')
    }
  } finally {
    video.deleting = false
  }
}

// 页面变化处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchVideos()
}

// 状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'published': return 'success'
    case 'draft': return 'warning'
    default: return 'info'
  }
}

// 状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'published': return '게시됨'
    case 'draft': return '초안'
    default: return '알 수 없음'
  }
}

// 格式化文件大小
const formatFileSize = (bytes: string | number | null) => {
  if (!bytes) return '-'
  const size = typeof bytes === 'string' ? parseInt(bytes) : bytes
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
  if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(1) + ' MB'
  return (size / (1024 * 1024 * 1024)).toFixed(1) + ' GB'
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('ko-KR')
}

// 移除文件
const removeVideoFile = () => {
  videoFileList.value = []
  if (videoInput.value) videoInput.value.value = ''
}

const removeCoverFile = () => {
  coverFileList.value = []
  if (coverInput.value) coverInput.value.value = ''
}

// 组件挂载时获取数据
onMounted(() => {
  fetchVideos()
  fetchChannels()
})
</script>

<template>
  <div class="mobile-video-management">
    <!-- 搜索栏 -->
    <div class="mobile-search-section">
      <el-input
        v-model="search"
        placeholder="비디오 제목 검색"
        :prefix-icon="Search"
        clearable
        @keyup.enter="handleSearch"
        @clear="clearSearch"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch" :loading="loading" />
        </template>
      </el-input>
    </div>

    <!-- 操作按钮 -->
    <div class="mobile-action-section">
      <el-button type="primary" :icon="Plus" @click="openUpload" size="large" style="width: 100%;">
        비디오 업로드
      </el-button>
    </div>

    <!-- 비디오 列表 -->
    <div class="mobile-videos-list" v-loading="loading">
      <!-- 空状态 -->
      <div v-if="!hasVideos && !loading" class="mobile-empty">
        <el-icon class="mobile-empty-icon" size="48">
          <VideoPlay />
        </el-icon>
        <div class="mobile-empty-text">
          {{ isSearching ? '검색 결과가 없습니다' : '비디오가 없습니다' }}
        </div>
        <el-button v-if="!isSearching" type="primary" :icon="Plus" @click="openUpload" style="margin-top: 16px;">
          첫 번째 비디오 업로드
        </el-button>
      </div>

      <!-- 비디오 卡片列表 -->
      <div v-else class="video-cards">
        <div v-for="video in videos" :key="video.id" class="mobile-video-card">
          <!-- 비디오 头部信息 -->
          <div class="video-header">
            <div class="video-cover">
              <img
                v-if="video.coverUrl"
                :src="`${API_BASE_URL}${video.coverUrl}`"
                alt="비디오 커버"
                class="cover-image"
              />
              <el-icon v-else class="cover-placeholder" size="32">
                <VideoPlay />
              </el-icon>
            </div>
            <div class="video-info">
              <div class="video-title">{{ video.title }}</div>
              <div class="video-channel">{{ video.channel?.name || '채널 없음' }}</div>
              <div class="video-meta">
                <el-tag :type="getStatusType(video.status)" size="small">
                  {{ getStatusText(video.status) }}
                </el-tag>
                <span class="video-size">{{ formatFileSize(video.sizeBytes) }}</span>
              </div>
            </div>
          </div>

          <!-- 비디오 详细信息 -->
          <div class="video-details" v-if="video.description">
            <div class="detail-item">
              <span class="detail-label">설명:</span>
              <span class="detail-value">{{ video.description }}</span>
            </div>
          </div>
          <div class="video-details">
            <div class="detail-item">
              <span class="detail-label">ID:</span>
              <span class="detail-value">{{ video.id }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">생성 시간:</span>
              <span class="detail-value">{{ formatDate(video.createdAt) }}</span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="video-actions">
            <el-button
              :icon="Delete"
              size="small"
              type="danger"
              @click="deleteVideo(video)"
              :loading="video.deleting"
            >
              삭제
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > pageSize" class="mobile-pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handlePageChange"
        small
      />
    </div>

    <!-- 隐藏的文件输入 -->
    <input
      ref="videoInput"
      type="file"
      accept="video/*"
      style="display: none"
      @change="handleVideoSelect"
    />
    <input
      ref="coverInput"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleCoverSelect"
    />

    <!-- 업로드 대화상자 -->
    <el-dialog
      v-model="showUploadDialog"
      title="비디오 업로드"
      width="95%"
      :close-on-click-modal="false"
      class="mobile-dialog"
    >
      <el-form :model="uploadForm" label-position="top" class="mobile-form">
        <el-form-item label="비디오 제목" required>
          <el-input
            v-model="uploadForm.title"
            placeholder="비디오 제목을 입력하세요"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="설명">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="비디오 설명을 입력하세요 (선택사항)"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="채널 선택" required>
          <el-select
            v-model="uploadForm.channelId"
            placeholder="채널을 선택하세요"
            style="width: 100%"
          >
            <el-option
              v-for="channel in channels"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="비디오 파일" required>
          <div class="mobile-file-section">
            <div class="file-selector" @click="selectVideo">
              <el-icon size="32">
                <VideoPlay />
              </el-icon>
              <div class="file-text">
                <div v-if="videoFileList.length === 0" class="file-placeholder">
                  비디오 파일 선택
                </div>
                <div v-else class="file-selected">
                  {{ videoFileList[0].name }}
                </div>
              </div>
              <el-button
                v-if="videoFileList.length > 0"
                :icon="Delete"
                circle
                size="small"
                type="danger"
                @click.stop="removeVideoFile"
              />
            </div>
            <div class="file-tips">
              <p>• 지원 형식: MP4, MOV</p>
              <p>• 최대 크기: 2GB</p>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="커버 이미지 (선택사항)">
          <div class="mobile-file-section">
            <div class="file-selector" @click="selectCover">
              <el-icon size="32">
                <Picture />
              </el-icon>
              <div class="file-text">
                <div v-if="coverFileList.length === 0" class="file-placeholder">
                  커버 이미지 선택
                </div>
                <div v-else class="file-selected">
                  {{ coverFileList[0].name }}
                </div>
              </div>
              <el-button
                v-if="coverFileList.length > 0"
                :icon="Delete"
                circle
                size="small"
                type="danger"
                @click.stop="removeCoverFile"
              />
            </div>
            <div class="file-tips">
              <p>• 지원 형식: JPG, PNG, WebP</p>
              <p>• 최대 크기: 10MB</p>
            </div>
          </div>
        </el-form-item>


      </el-form>

      <template #footer>
        <div class="mobile-dialog-footer">
          <el-button @click="showUploadDialog = false" size="large">취소</el-button>
          <el-button
            type="primary"
            @click="uploadVideo"
            :loading="uploading"
            :disabled="!canUpload"
            size="large"
          >
            업로드
          </el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<style scoped>
/* 移动端비디오 관리主容器 */
.mobile-video-management {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
}

/* 搜索区域 */
.mobile-search-section {
  background: var(--el-bg-color);
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

/* 操作按钮区域 */
.mobile-action-section {
  padding: 0 16px;
}

/* 비디오 列表容器 */
.mobile-videos-list {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

/* 空状态 */
.mobile-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: var(--el-text-color-placeholder);
  text-align: center;
}

.mobile-empty-icon {
  color: var(--el-color-info);
  margin-bottom: 16px;
}

.mobile-empty-text {
  font-size: 16px;
  margin-bottom: 8px;
}

/* 비디오 卡片容器 */
.video-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 0 16px;
}

/* 移动端비디오 卡片 */
.mobile-video-card {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.mobile-video-card:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 비디오 头部信息 */
.video-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.video-cover {
  width: 80px;
  height: 45px;
  border-radius: 8px;
  overflow: hidden;
  background: var(--el-fill-color-light);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-placeholder {
  color: var(--el-text-color-placeholder);
}

.video-info {
  flex: 1;
  min-width: 0;
}

.video-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
  word-break: break-word;
  line-height: 1.4;
}

.video-channel {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-bottom: 8px;
}

.video-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.video-size {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

/* 비디오 详细信息 */
.video-details {
  margin-bottom: 16px;
  padding: 12px;
  background: var(--el-fill-color-extra-light);
  border-radius: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  font-size: 14px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: var(--el-text-color-regular);
  font-weight: 500;
  flex-shrink: 0;
  margin-right: 8px;
}

.detail-value {
  color: var(--el-text-color-primary);
  text-align: right;
  word-break: break-word;
}

/* 비디오 操作按钮 */
.video-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.video-actions .el-button {
  min-width: 60px;
}

/* 分页 */
.mobile-pagination {
  display: flex;
  justify-content: center;
  padding: 16px;
  background: var(--el-bg-color);
  border-radius: 12px;
  margin: 0 16px;
}

/* 移动端对话框样式 */
.mobile-dialog {
  margin: 5vh auto;
}

.mobile-form {
  padding: 0;
}

.mobile-form .el-form-item {
  margin-bottom: 20px;
}

.mobile-form .el-form-item__label {
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

/* 移动端文件选择器 */
.mobile-file-section {
  width: 100%;
}

.file-selector {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border: 2px dashed var(--el-border-color);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: var(--el-bg-color);
  position: relative;
}

.file-selector:hover {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
}

.file-selector .el-icon {
  color: var(--el-text-color-placeholder);
  flex-shrink: 0;
}

.file-text {
  flex: 1;
  min-width: 0;
}

.file-placeholder {
  color: var(--el-text-color-placeholder);
  font-size: 14px;
}

.file-selected {
  color: var(--el-text-color-primary);
  font-size: 14px;
  font-weight: 500;
  word-break: break-word;
}

.file-tips {
  margin-top: 12px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  line-height: 1.5;
}

.file-tips p {
  margin: 0;
}

/* 移动端对话框底部 */
.mobile-dialog-footer {
  display: flex;
  gap: 12px;
  padding: 16px 0 0 0;
}

.mobile-dialog-footer .el-button {
  flex: 1;
}

/* 暗黑模式适配 */
:root.dark .mobile-video-card {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}

:root.dark .file-selector {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}

:root.dark .file-selector:hover {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-dark-2);
}

:root.dark .video-details {
  background: var(--el-fill-color-darker);
}
</style>
